package com.migrate.module.config;
import com.migrate.module.sharding.MigrateConfig;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 迁移代码相关数据源配置
 *
 * @author zhonghuashishan
 */
@Configuration
@MapperScan(basePackages = "com.migrate.module.mapper.migrate", sqlSessionTemplateRef  = "MigrateSqlSessionTemplate")
public class MigrateDataSourceConfig extends AbstractDataSourceConfig{
    @Autowired
    private MigrateConfig migrateConfig;

    @Bean(name = "MigrateDataSource")
    @Primary
    public DataSource dataSource() {
        return buildDruidDataSource(migrateConfig.getMigrateDatasource());
    }

    @Bean(name = "MigrateSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("MigrateDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage ("com.migrate.module.domain");
        bean.setConfigLocation (new ClassPathResource("mybatis/mybatis-config.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/migrate/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "MigrateTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("MigrateDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "MigrateSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("MigrateSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
